package com.googlecode.wickedforms.xvergabe;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Locale;

import org.apache.wicket.model.Model;
import org.apache.xmlbeans.XmlException;
import org.xvergabe.xsd.forms.components.x20.DisplayInformation;
import org.xvergabe.xsd.forms.components.x20.FormDocument.Form;
import org.xvergabe.xsd.forms.components.x20.RoleType;

import com.googlecode.wickedforms.model.FormModel;
import com.googlecode.wickedforms.wicket6.components.FormPanel;
import com.googlecode.wickedforms.xvergabe.modelers.FormModeller;
import com.googlecode.wickedforms.xvergabe.togglestamper.ActivationToggleStamper;
import com.googlecode.wickedforms.xvergabe.xml.FormXmlReader;
import com.googlecode.wickedforms.xvergabe.xml.FormXmlStreamReader;

public class FormPage extends BasePage {

	private static final long serialVersionUID = 1L;

	public static final Locale germany = new Locale("de", "DE");

	public RoleType.Enum displayMode = RoleType.PROVIDER;

	public FormPage(final FormParameters formParameters) {

		try {

			// read xml
			FormXmlReader xmlReader = new FormXmlStreamReader(
					new ByteArrayInputStream(formParameters.getXml().getBytes()));
			Form xmlForm = xmlReader.readFromXml();

			// convert xml to model
			if (formParameters.getDisplayMode() != null) {
				this.displayMode = formParameters.getDisplayMode();
			}

			DisplayInformation[] displayInformationArray = xmlForm.getMetadata().getDisplayInformationArray();
			String formTitle = displayInformationArray[0].getLabel().getStringValue();
			
			FormModeller formModeller = new FormModeller(formTitle);
			FormModel formModel = formModeller.createModelFromXml(xmlForm,
					formParameters.getLocale(), this.displayMode);
			formModel.assignIds();

			ActivationToggleStamper activationToggleStamper = new ActivationToggleStamper();
			activationToggleStamper.stampActivationToggles(xmlForm.getMetadata(),formModel);
			
			
			
			// add model to form page
			add(new FormPanel("dynoForm", Model.of(formModel)) {

				@Override
				public void onSubmit(final FormModel submittedData) {
					// TODO -> Sinnvolle Übergabeparameter
					System.out.println("something usefull");
				}

			});
		} catch (XmlException e) {
			throw new RuntimeException(e);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}

	}
}
